package com.youhui.weixin.utils.weixin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youhui.weixin.common.MythConfig;
import com.youhui.weixin.common.exception.MythException;
import com.youhui.weixin.common.info.MythExceptionList;
import com.youhui.weixin.domain.AccessToken;
import com.youhui.weixin.weixin.domain.Button;
import com.youhui.weixin.weixin.domain.ClickButton;
import com.youhui.weixin.weixin.domain.Menu;
import com.youhui.weixin.weixin.domain.ViewButton;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.youhui.weixin.utils.weixin.WXConfig.*;

/**
 * Created by https://github.com/kuangcp on 17-10-15  下午5:11
 * 关于微信公众号自定义菜单的工具类
 */
@Log4j
@Component
public class WXMenuUtils {

    private static ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 初始化菜单，后期应该使用配置文件，或者写死不动了？
     */
    private Menu initMenu(){


        Menu menu = new Menu();
//        ClickButton clickButton = new ClickButton();
//        clickButton.setName("免费领优惠券");
//        clickButton.setType("click");
//        clickButton.setKey("11");

        ViewButton main = new ViewButton();
        main.setName("天猫券");
        main.setType(WXConfig.MENU_VIEW);
        main.setUrl("http://wx.jjyouhuigo.com/");

        ViewButton search = new ViewButton();
        search.setName("腾讯券");
        search.setType(WXConfig.MENU_VIEW);
        search.setUrl("https://share.chuchutong.com/d/DmGNJEmn");

        ViewButton clickButton1 = new ViewButton();
        clickButton1.setName("反馈建议");
        clickButton1.setType(WXConfig.MENU_VIEW);
        clickButton1.setUrl("http://wx.jjyouhuigo.com/feedback");

        ViewButton clickButton2 = new ViewButton();
        clickButton2.setName("使用指南");
        clickButton2.setType(WXConfig.MENU_VIEW);
        clickButton2.setUrl("http://wx.jjyouhuigo.com/help");

        Button button = new Button();
        button.setName("指南");
        button.setSub_button(new Button[]{clickButton1, clickButton2});

        menu.setButton(new Button[]{main, search, button});
        return  menu;
    }


    /**
     * 获取token，如果已经获取了就不去获取
     * @return token字符串
     * @throws MythException 异常就表示失败
     */
    private String getToken() throws MythException{
        String token;
        // 如果redis中存有token 且具有最小时效就直接读取redis
        if (stringRedisTemplate.getExpire(MythConfig.ACCESS_TOKEN).intValue() > MythConfig.MIN_TOKEN_EXPIRE){
            return stringRedisTemplate.opsForValue().get(MythConfig.ACCESS_TOKEN);
        }
        String url = ACCESS_TOKEN_URL.replace("APPID", APP_ID);
        url = url.replace("APPSECRET", APP_SECRET);
        try{
            String result = HttpUtils.get(url);

            AccessToken accessToken = mapper.readValue(result, AccessToken.class);
            token = accessToken.getAccess_token();

            stringRedisTemplate.opsForValue().set(MythConfig.ACCESS_TOKEN, token, accessToken.getExpires_in(), TimeUnit.SECONDS);
        }catch (IOException e){
            throw new MythException(MythExceptionList.REQUEST_FAILED, e, WXMenuUtils.class);
        }
        return token;
    }

    /**
     * 读取token 调用创建菜单的方法
     * @throws MythException 异常
     */
    public void createMenu() throws MythException {
        int result;
        try {
            String token  = getToken();
            String menuJson = mapper.writeValueAsString(initMenu());
            menuJson = new String(menuJson.getBytes("utf-8"));

            result = postCreateMenu(token, menuJson);
            log.info(menuJson+"\n返回码："+result);
        } catch (Exception e) {
            throw new MythException(MythExceptionList.CREATE_MENU_FAILED, e, WXMenuUtils.class);
        }
        if (result != 0){
            throw new MythException(MythExceptionList.CREATE_MENU_FAILED, WXMenuUtils.class);
        }

    }
    /**
     * 使用token来校验，创建菜单，私有化
     * @param token token
     * @param menu 菜单对象的json字符串
     * @return 0成功，非0失败
     * @throws MythException 读取json异常
     */
    private int postCreateMenu(String token, String menu) throws MythException {
        String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
        ObjectMapper mapper = new ObjectMapper();
        String response;
        Map map;
        try {
            response = HttpUtils.post(url, menu);
            map = mapper.readValue(response, Map.class);
        } catch (IOException e) {
            throw new MythException(MythExceptionList.IO_READ_JSON_EXCEPTION, e, WXMessagesUtils.class);
        }
        if (map != null) {
            return Integer.parseInt(map.get("errcode").toString());
        }else{
            return 1;
        }
    }
}
